import { Button, Divider, message, Table, TableProps } from "antd";
import { useState } from "react";
import styles from './index.less';
import { useColumns } from "./hooks/useColumns";
import { calculateCartTotalPrice, getCarList, removeCar } from "@/services/shoppingCar";
import modal from "antd/es/modal";
import { favoriteGoods } from "@/services/details";
import { money } from "@/utils/money";
import { useRequest } from "ahooks";
import { history } from '@umijs/max';

const MyShoppingCar = () => {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const [ total, setTotal] = useState<number>(0)
    const [selectRow, setSelectRow] = useState<any[]>([])
    
    const rowSelection: TableProps<any>['rowSelection'] = {
        onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
            calculateCartTotalPrice({goodsList: selectedRows}).then((res) => {
                if (res.code === 200) {
                    setTotal(res.data)
                }
            })
            setSelectRow(selectedRows)
        },
      };
      const {data, run: getList} = useRequest(() => {
        return getCarList({userId: userInfo.id}).then((res) => {
            if (res.code === 200) {
                return res.data;
            } else {
                message.warning(res.message)
            }
        })
      })
      const addCollect = (item) => {
        const data = {
            goodsId: item?.goodsId,
            userId: item?.userId,
            skuId: item?.id,
        }
        favoriteGoods(data).then((res) => {
            if (res.code === 200) {
                message.success('收藏成功')
            } else {
                message.warning(res.message)
            }
        })
      }
      const deleteCar = (item) => {
        modal.confirm({
            title: "确定要将商品移出购物车吗？",
            onOk() {
                removeCar({cartIds: [item.id]}).then((res) => {
                if (res.code === 200) {
                  getList()
                  message.success("移出成功");
                }
              })
            },
          });
      }
      const columns = useColumns({deleteCar, addCollect})
     
      const goCreateOrder = () => {
        history.push('/createOrder', {
            skuList: selectRow.map((item) => {
                return {
                    ...item,
                    name: item.skuName
                }
            })
        })
      }
    return (
        <div>
            <Divider style={{ borderColor: "#7cb305" }} orientation="start">
                我的购物车
            </Divider>
            <div className={styles.content}>
                <Table
                    rowSelection={{ type: 'checkbox', ...rowSelection }}
                    columns={columns}
                    dataSource={data}
                    pagination={false}
                />
            </div>
            <div className={styles.bottom}>
                <div>
                    已经选择<span style={{ color: 'red' }}>{selectRow?.length || 0}</span>件商品
                </div>
                <div style={{ marginInline: 20, display: 'flex', alignItems: 'center' }}>
                    总价：<span style={{ fontSize: 24, color: 'red' }}>¥：{money(total?.totalPrice)}</span>
                </div>
                <Button type="primary" size="large" onClick={goCreateOrder}>去结算</Button>
            </div>
        </div>
    )
}

export default MyShoppingCar;